﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json.Linq;
using System.Net;
using System.IO;
using System.Text;

namespace OTPlus
{
    public partial class login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["error"] != null)
            {
                this.lblResponse.Text = "Error returned by google. No access provided; aborting.";
            }
            else
            {
                //http://code.google.com/apis/accounts/docs/OAuth2WebServer.html
                //***Handling The Response


                String accesscode = Request.QueryString["code"];
                this.gettokens(accesscode);
            }
        }

        private void gettokens(String code)
        {
            String result = String.Empty;

            string clientid = System.Configuration.ConfigurationManager.AppSettings["gplusclientid"];
            string clientsecret = System.Configuration.ConfigurationManager.AppSettings["gplusclientsecret"];
            string clientredirecturi = System.Configuration.ConfigurationManager.AppSettings["gplusclientredirecturi"];

            String payload = "code=" + code +
                "&client_id=" + clientid +
                "&client_secret=" + clientsecret +
                "&redirect_uri=" + clientredirecturi +
                "&grant_type=authorization_code";

            try
            { 
                result = this.sendRequest("https://accounts.google.com/o/oauth2/token", "POST", payload);
                
            }
            catch(Exception exc)
            {
                throw exc;
            }


            //this.lblResponse.Text = result;

            JObject jo = JObject.Parse(result);
            Session.Add("access_token", jo["access_token"]);


            //this.lblResponse.Text = Session["access_token"].ToString();

            Response.Redirect("/default.aspx");

        }

        private string sendRequest(string url, string method, string postdata)
        {
            WebRequest rqst = HttpWebRequest.Create(url);

            rqst.Method = method;
            if (!String.IsNullOrEmpty(postdata))
            {
                rqst.ContentType = "application/x-www-form-urlencoded";

                byte[] byteData = UTF8Encoding.UTF8.GetBytes(postdata);
                rqst.ContentLength = byteData.Length;
                
                using (Stream postStream = rqst.GetRequestStream())
                {
                    postStream.Write(byteData, 0, byteData.Length);
                    postStream.Close();
                }
            }
            ((HttpWebRequest)rqst).KeepAlive = false;
            ((HttpWebRequest)rqst).AllowWriteStreamBuffering = true;

            try
            {
                WebResponse response = rqst.GetResponse();

                StreamReader rsps = new StreamReader(response.GetResponseStream());

                string strRsps = rsps.ReadToEnd();
                return strRsps;
            }
            catch (Exception exc)
            {
                throw exc;
            }

        }
    }
}